//
//  HZMallCartsHttpManager.m
//  app
//
//  Created by 刘华舟 on 15/5/5.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallCartsHttpManager.h"
#import "HZHttpRequestURL.h"
//model
#import "HZRemoteResult.h"
#import "HZCartListVCModel.h"
#import "HZOrderConfirmVCModel.h"
#import "HZOrderByerAddrVCData.h"




#import "JSONKit.h"


static NSString *kMallCartHttpCookies = @"MallCartHttpCookies";
static NSString *const kMallCartListDictNSDataIntervalFormmat = @"MallCartListDictNSDataIntervalFormmat";
static NSString *const kMallSearchNSDataIntervalFormmat = @"kMallSearchNSDataIntervalFormmat";
static float kMallAddressDataCacheValidableTime = 24*60*60.0f;

static float kMallHttpAfterDelayTimeInterval = 0.2f;


static HZMallCartsHttpManager *_mallCartsHttpManager = nil;

@interface HZMallCartsHttpManager()

@property (strong, nonatomic) JKHttpClient *http;

@property (strong, nonatomic) AFNetworkReachabilityManager *reachabilityManager;


@end

@implementation HZMallCartsHttpManager

+ (instancetype)shareHttpRequestMananger{
    if (_mallCartsHttpManager == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _mallCartsHttpManager = [[self alloc] initManager];
        });
    }
    return _mallCartsHttpManager;
}

- (instancetype)initManager{
    if (self = [super init]) {
        self.http = [[JKHttpClient alloc] init];
        self.sqlManager = [HZMallSqlDataManager defaultManager];
        self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];

    }
    _mallCartsHttpManager = self;
    return _mallCartsHttpManager;
}
//是否网络通
- (BOOL)networkReachable{
    return self.reachabilityManager.isReachable;
}
//获取购物车列表
- (void)loadMallCartListDataWithResult:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_cartListUrl];
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].sbpd_cartListUrl params:nil
            result:^(JKResponse *result) {
                
                //同步本地与服务器的时间差
                [result refreshTheDifferentOfNativeTimeAndWebTime];
                
                if (result.OK) {
                    HZCartListVCModel *model = [[HZCartListVCModel alloc] initWithJSONData:result.content];
                    remote.info = model;
                    
                    if (result.isTail) {
                        model.noMoreData = YES;
                    }
                }
                
                [remote call:result];
            }];
}

//删除购物车列表中商品
- (void)deleteGoodsWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_carListDeleteUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbpd_carListDeleteUrl params:params
            result:^(JKResponse *result) {
                [remote call:result];
            }];
}

//添加购物车列表中商品
- (void)addGoodsWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_carListAddUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbpd_carListAddUrl params:params
            result:^(JKResponse *result) {
                [remote call:result];
            }];
}

//拉取我的订单确认之前数据
- (void)loadOrderConfirmDataWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_orderConfirmUrl];
    
    
    //请求数据
    [self.http get:[SNUniteUrl shareUniteUrl].sbpd_orderConfirmUrl params:params
            result:^(JKResponse *result) {
                
                if (result.OK) {
                    HZOrderConfirmVCModel *model = [[HZOrderConfirmVCModel alloc] initModelWithDictionary:result.content];
                    remote.info = model;
                    if (result.isTail) {
                        model.noMoreData = YES;
                    }
                }
                [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];

            }];

}

//确认我的订单（下单）
- (void)createOrderDataWithParams:(NSDictionary *)params result:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    [self.http showMaskWithMessage:@"订单生成中"];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].sbpd_orderCommitUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].sbpd_orderCommitUrl params:params
            result:^(JKResponse *result) {
                
                if (result.OK) {
                    remote.info = result.content;
                }
                [remote performSelector:@selector(call:) withObject:result afterDelay:kMallHttpAfterDelayTimeInterval];
            }];
}


////获取订单付款方式和配送信息
//- (void)loadOrderPayAndExpWithResult:(HZRemoteResult *)remote{
//    
//    [self.http showNetUnReachableToast];
//    
//    //发起请求之前先取消之前的请求
//    [self.http cancel:kOrderPayAndExpHttpRequestURL];
//    
//    //请求数据
//    [self.http post:kOrderPayAndExpHttpRequestURL params:nil
//             result:^(JKResponse *result) {
//                 
//                 if (result.OK) {
//                     remote.info = result.content;
//                 }
//                 [remote call:result];
//             }];
//}
//
////获取个人的发票信息
//- (void)loadOrderInvoiceInfoWithResult:(HZRemoteResult *)remote{
//    
//    [self.http showNetUnReachableToast];
//    
//    //发起请求之前先取消之前的请求
//    [self.http cancel:kOrderInvoiceInfoHttpRequestURL];
//    
//    //请求数据
//    [self.http post:kOrderInvoiceInfoHttpRequestURL params:nil
//             result:^(JKResponse *result) {
//                 
//                 if (result.OK) {
//                     remote.info = [result.content arrayForKey:APIKEY_mall_invoice_type];
//                 }
//                 [remote call:result];
//             }];
//}


//获取个人所有收货地址信息
- (void)loadOrderAllUserAddressInfoWithResutl:(HZRemoteResult *)remote cache:(BOOL)flag{
    
    //判定是否需要本地缓存数据(本地缓存实效则从网络拉取)
    if (flag) {
        
        NSString *dataTimeStamp = [self.sqlManager queryForAddressCacheDataTemptime];
        
        NSArray *dictArray = [self.sqlManager queryForAllUserAddress];
        
        
        
        NSDictionary *responeDict = @{APIKEY_mall_ret:@0, APIKEY_mall_msg:@"ok",APIKEY_mall_timestamp:dataTimeStamp, APIKEY_mall_result:dictArray};
        
        
        JKResponse *result = [[JKResponse alloc] initWithResponse:[responeDict JSONData] req:nil];
        
        HZOrderByerAddrVCData *data = [HZOrderByerAddrVCData dataWithDictionary:result.content];
        remote.info = data;
        
        [remote call:result];
        
        float time = ([NSDate date].timeIntervalSince1970 - [dataTimeStamp floatValue]);
        if ( time < kMallAddressDataCacheValidableTime) {
            return;
        }
    }
    
    [self.http showNetUnReachableToast];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].per_userAllAddressInfoUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].per_userAllAddressInfoUrl params:nil
             result:^(JKResponse *result) {
                 
                 if (result.OK) {
                     HZOrderByerAddrVCData *data = [HZOrderByerAddrVCData dataWithDictionary:result.content];
                     data.timestamp = [NSString stringWithFormat:@"%ld", result.timestamp];
                     data.message = result.message;
                     remote.info = data;
                     
                     //跟新数据库
                     [self.sqlManager updateUserAllAddressWithModel:data.addressArray temptime:data.timestamp];
                 }
                 [remote call:result];
             }];
}

//删除个人收货地址信息
- (void)deleteUserAddressInfoWithParams:(NSDictionary *)params resutl:(HZRemoteResult *)remote{
    
    //删除个人信息地址
    HZOrderByerAddressModel *model = [HZOrderByerAddressModel modelWithDictionary:params];
    [self.sqlManager deleteUserAddressWithModel:model];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].per_deleteUserAddressUrl];
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].per_deleteUserAddressUrl params:params
             result:^(JKResponse *result) {
                 [remote call:result];
             }];

}

//新增个人收货地址信息（默认设置为默认收货地址）
- (void)addUserAddressInfoWithParams:(NSDictionary *)params resutl:(HZRemoteResult *)remote{
    
    [self.http showNetUnReachableToast];
    
    [self.http showMaskWithMessage:@"添加中"];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].per_addUserAddressUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].per_addUserAddressUrl params:params
             result:^(JKResponse *result) {
                 remote.info = result.content;
                 //新增个人信息地址
                 HZOrderByerAddressModel *model = [HZOrderByerAddressModel modelWithDictionary:remote.info];
                 [self.sqlManager addNewUserDefaultAddressWithModel:model temptime:nil];
                 
                 [remote call:result];
             }];
}

//修改个人收货地址信息(包括设置默认)
- (void)modifyUserAddressInfoWithParams:(NSDictionary *)params resutl:(HZRemoteResult *)remote mask:(BOOL)isNeedMask{
    
    [self.http showNetUnReachableToast];
    
    if (isNeedMask) {
        [self.http showMaskWithMessage:@"修改中"];
    }
    
    
    
    //修改个人信息地址
    HZOrderByerAddressModel *model = [HZOrderByerAddressModel modelWithDictionary:params];
    
    [self.sqlManager updateUserDefaultAddressWithModel:model temptime:nil];
    
    //发起请求之前先取消之前的请求
    [self.http cancel:[SNUniteUrl shareUniteUrl].per_modifyUserAddressUrl];
    
    //请求数据
    [self.http post:[SNUniteUrl shareUniteUrl].per_modifyUserAddressUrl params:params
             result:^(JKResponse *result) {
                 remote.info = [result.content dictForKey:APIKEY_mall_result];
                 [remote call:result];
             }];
}





@end
